<?php
class Shangku_Orderpayment_IndexController extends Mage_Core_Controller_Front_Action
{
	private function _convertToQuote(Mage_Sales_Model_Order $order)
	{
		$convert = Mage::getModel('sales/convert_order');
		
		$quoteShippingAddress = $convert->addressToQuoteAddress($order->getShippingAddress());
		$quoteBillingAddress = $convert->addressToQuoteAddress($order->getBillingAddress());
		$quotePayment = $convert->paymentToQuotePayment($order->getPayment());
		$quoteShippingAddress->setShippingMethod($order->getShippingMethod());
		$quote = $convert->toQuote($order);

		$quote->getPayment()->importData($quotePayment->getData());
		$quote->setShippingAddress($quoteShippingAddress)
			->setBillingAddress($quoteBillingAddress);
		if ($quote->isVirtual()) {
			$quote->getBillingAddress()->setPaymentMethod($order->getPayment()->getMethod());
		} else {
			$quote->getShippingAddress()->setPaymentMethod($order->getPayment()->getMethod());
		}
		
		$this->getCheckoutSession()->clear();
		$this->getCheckoutSession()->replaceQuote($quote);
		
		$cart = $this->getCart();
		foreach($order->getItemsCollection() as $item){
			$cart->addOrderItem($item);
		}
		$cart->save();
		
		return $this->getCheckoutSession()->getQuote();
	}
	public function getCart()
	{
		return Mage::getSingleton('checkout/cart');
	}
 	public function getCheckoutSession()
    {
        return Mage::getSingleton('checkout/session');
    }
	public function indexAction()
	{
		$orderId = (int)$this->getRequest()->getParam('order_id', 0);
		$order = Mage::getModel('sales/order')->load($orderId);
		if(!$order){
			$this->_redirectUrl(Mage::getUrl('/'));
			return;
		}

		$status = $order->getState();
		$canPayStatus = array(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, Mage_Sales_Model_Order::STATE_CANCELED);
		if(!in_array($status, $canPayStatus)){
			$this->_redirectUrl(Mage::getUrl('/'));
			return;
		}
		
		//convert order  to a new quote
		$quote = $this->_convertToQuote($order);

		//update quote id
		$order->setQuoteId($quote->getId())->save();
		
		$this->getCheckoutSession()->setLastOrderId($order->getId())
			->setLastRealOrderId($order->getIncrementId());

		if(!$redirectUrl = $quote->getPayment()->getOrderPlaceRedirectUrl()){
			$redirectUrl = Mage::getUrl('/');
		}
		
		$this->_redirectUrl($redirectUrl);
		return;
	}
}
